package com.ihome.android.academy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ihome.android.EAActivity;
import com.ihome.android.EAApp;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.dl.core.DownloadHelper;
import com.ihome.android.dl.core.DownloadTask;
import com.ihome.android.dl.util.DLFileInfo;
import com.ihome.android.dl.util.DownloadValues;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.adapter.FragmentAdapter;
import com.ihome.android.market2.asynctask.GetAppUrlTask;
import com.ihome.android.market2.asynctask.InstallAppTask;
import com.ihome.android.market2.frag.DownloadingAppFragment;
import com.ihome.android.market2.frag.InstalledAppFragment;
import com.ihome.android.market2.frag.UpdateAppFragment;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.LogoTop;
import com.ihome.android.market2.view.PageLine;
import com.ihome.android.util.AppUtils;
import com.ihome.android.util.BgInstallApk;
import com.ihome.android.util.Util;
import com.ihome.android.util.log.LogUtil;

public class AppMgrActivity extends EAActivity implements OnKeyListener, OnClickListener, OnFocusChangeListener {
	private String					TAG				= AppMgrActivity.class.getSimpleName();

	@EAInjectView(id = R.id.app_topline)
	private LogoTop					mLogoTop;

	@EAInjectView(id = R.id.vp_fragment)
	private ViewPager				vp_fragment;

	@EAInjectView(id = R.id.app_mgr_pageline)
	private PageLine				mPageLine;
	@EAInjectView(id = R.id.app_separate_line)
	private LinearLayout			app_separate_line;
	@EAInjectView(id = R.id.cb_app_installed)
	private CheckBox				cb_app_installed;
	@EAInjectView(id = R.id.cb_app_downloading)
	private CheckBox				cb_app_downloading;
	@EAInjectView(id = R.id.cb_app_update)
	private CheckBox				cb_app_update;
	@EAInjectView(id = R.id.tv_app_dling_num)
	private TextView				tv_app_dling_num;
	@EAInjectView(id = R.id.tv_app_update_num)
	private TextView				tv_app_update_num;

	@EAInjectView(id = R.id.sd_capacity)
	private TextView				sd_capacity;

	private InstalledAppFragment	mInstallAppFrag;
	private DownloadingAppFragment	mDownloadingAppFrag;
	private UpdateAppFragment		mUpdateAppFrag;

	private List<Fragment>			mFraglist;
	private int						curPosition		= 0;
	private int						totalPage		= 0;

	/** 每页展示的APP数量 */
	private final int				APPNUM_PER_PAGE	= 9;

	/** 当前正在卸载的应用包名 */
	public String					opratePkgName	= "";
	/** 当前正在操作的AppInfo */
	public AppInfo					mAppInfo;
	private Handler					mHandler;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				DownloadTask task = null;
				if (msg.obj instanceof DownloadTask) {
					task = (DownloadTask) msg.obj;
				}

				switch (msg.what) {
				case DownloadValues.Types.COMPLETE:
					handleCompletedAction(task.getAppInfo());
					break;
				case DownloadValues.Types.PROCESS:
					handleProgress(task.getAppInfo());
					break;
				case DownloadValues.Types.ERROR:
					handleError(task.getAppInfo(), task.getErrorCode(), task.getErrorInfo());
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_mgr);
		procHandler();
		init();
		checkInstalledDLApp();
		EAApp.getApp().addHandler(mHandler);
	}

	@Override
	protected void onResume() {
		super.onResume();
		sdcard();
	}

	@Override
	public void finish() {
		super.finish();
		EAApp.getApp().clearHandler(mHandler);
	}

	private void sdcard() {
		long sdAvailable = Util.getAvailableInternalMemorySize() / (1024 * 1024);
		long sdTotal = Util.getTotalInternalMemorySize() / (1024 * 1024);
		LogUtil.v(TAG, "sdAvailable = " + sdAvailable + "; sdTotal = " + sdTotal);
		if (sdTotal > 0) {
			sd_capacity.setText(Html.fromHtml(getString(R.string.sd_capacity_tvinfo, (sdTotal - sdAvailable), sdAvailable)));
		}
		else {
			sd_capacity.setVisibility(View.INVISIBLE);
		}
	}

	public void titleFocus() {
		LogUtil.v(TAG, " -->  titleFocus() ");
		//((CheckBox) ((RelativeLayout) app_separate_line.getChildAt(curPosition)).getChildAt(0)).requestFocus();
		((RelativeLayout) app_separate_line.getChildAt(curPosition)).requestFocus();
	}

	private void init() {
		LogUtil.i(TAG, " -->  init()");
		mLogoTop.setOnKeyListener(this);

		cb_app_installed.setOnClickListener(this);
		cb_app_downloading.setOnClickListener(this);
		cb_app_update.setOnClickListener(this);

		cb_app_installed.setOnFocusChangeListener(this);
		cb_app_downloading.setOnFocusChangeListener(this);
		cb_app_update.setOnFocusChangeListener(this);

		app_separate_line.setOnKeyListener(this);

		initViewPage();
	}

	private void initViewPage() {
		mFraglist = new ArrayList<Fragment>();

		mInstallAppFrag = new InstalledAppFragment();
		mDownloadingAppFrag = new DownloadingAppFragment();
		mUpdateAppFrag = new UpdateAppFragment();

		mFraglist.add(mInstallAppFrag);
		mFraglist.add(mDownloadingAppFrag);
		mFraglist.add(mUpdateAppFrag);

		vp_fragment.setAdapter(new FragmentAdapter(getSupportFragmentManager(), mFraglist));
		vp_fragment.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageSelected(int position) {
				curPosition = position;
				titleSelected(position);

				if (mFraglist.get(position) instanceof InstalledAppFragment) {
					((InstalledAppFragment) mFraglist.get(position)).initData();
				}
				if (mFraglist.get(position) instanceof DownloadingAppFragment) {
					((DownloadingAppFragment) mFraglist.get(position)).getDLingAppList();
				}
				if (mFraglist.get(position) instanceof UpdateAppFragment) {
					((UpdateAppFragment) mFraglist.get(position)).initData();
				}
			}

		});
		vp_fragment.setCurrentItem(0);
		titleSelected(0);
		titleFocus();
	}

	public void titleSelected(int position) {

		((CheckBox) ((RelativeLayout) app_separate_line.getChildAt(position)).getChildAt(0)).setChecked(true);

		for (int i = 0; i < app_separate_line.getChildCount(); i++) {
			if (i != position) {
				((CheckBox) ((RelativeLayout) app_separate_line.getChildAt(i)).getChildAt(0)).setChecked(false);
			}
		}
	}

	/**
	 * 设置页数和APP总数
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	public void setPageLine(int mCurPage, int mAppNum, int mCurPos) {
		if (mPageLine != null && mCurPos == curPosition)
			mPageLine.setPageNum(mCurPage, mAppNum, APPNUM_PER_PAGE, false);

		switch (mCurPos) {
		case 0:

			break;
		case 1:
			setDLingAppNoti(mAppNum);
			break;
		case 2:
			setUpdateAppNoti(mAppNum);
			break;

		default:
			break;
		}
	}

	/**
	 * 设置可升级APP数量
	 * 
	 * @param num
	 * @see [类、类#方法、类#成员]
	 */
	public void setDLingAppNoti(int num) {
		LogUtil.i(TAG, " -->  setDLingAppNoti() num = " + num);
		if (num > 0) {
			tv_app_dling_num.setText(num + "");
			tv_app_dling_num.setVisibility(View.VISIBLE);
		}
		else {
			tv_app_dling_num.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 设置可升级APP数量
	 * 
	 * @param num
	 * @see [类、类#方法、类#成员]
	 */
	public void setUpdateAppNoti(int num) {
		LogUtil.i(TAG, " -->  setUpdateAppNoti() num = " + num);
		if (num > 0) {
			tv_app_update_num.setText(num + "");
			tv_app_update_num.setVisibility(View.VISIBLE);
		}
		else {
			tv_app_update_num.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		//LogUtil.d(TAG, "mInstallAppFrag.isOnFirstLine() =" + mInstallAppFrag.isOnFirstLine());
		//LogUtil.d(TAG, "curPosition=" + curPosition + "; keyCode=" + keyCode + "; event.getAction()=" + event.getAction());

		if (mLogoTop.hasFocus() && (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN)) {
			titleFocus();
			return true;
		}

		return false;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		default:
			break;
		}

	}

	/**
	 * 卸载成功后的回调方法，需要清除已安装列表、可更新列表
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	public void uninstallationCheck() {
		LogUtil.i(TAG, " -->  uninstallationCheck()");
		if (mFraglist.get(curPosition) instanceof InstalledAppFragment) {
			mInstallAppFrag.uninstallationCheck(opratePkgName);
		}
		if (mFraglist.get(curPosition) instanceof UpdateAppFragment) {
			mUpdateAppFrag.uninstallationCheck(opratePkgName);
		}

		sdcard();
	}

	/**
	 * 应用安装成功后的回调方法，需要清除已安装列表
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	public void installationCheck(String pkgName) {
		if (mFraglist.get(curPosition) instanceof InstalledAppFragment) {
			mInstallAppFrag.installationCheck(pkgName);

		}
		if (mFraglist.get(curPosition) instanceof UpdateAppFragment) {
			mUpdateAppFrag.installationCheck(pkgName);
		}

		if (mFraglist.get(curPosition) instanceof DownloadingAppFragment) {
			mDownloadingAppFrag.installationCheck(pkgName);

		}


		checkInstalledDLApp();

		sdcard();
	}

	/**
	 * 
	 * 文件下载成功
	 * 
	 * @param dLFileInfo
	 * @see [类、类#方法、类#成员]
	 */
	private void handleCompletedAction(DLFileInfo dLFileInfo) {
		String filePath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
		LogUtil.d(TAG, "Download CompletedAction ---> filePath = " + filePath);

		if (AppUtils.checkAppInstallByPkgName(this, dLFileInfo.getPkgName())) {
			LogUtil.w(TAG, dLFileInfo.getPkgName() + "has installed");
		}
		else {
			LogUtil.w(TAG, dLFileInfo.getPkgName() + "is to install ....");
		}
		
		if (EAApp.isSystemApp) {
			LogUtil.w(TAG, "Sytem app");
			Bundle b = new Bundle();
			b.putString(HttpKeys.KEY_APKPATH, filePath);
			new InstallAppTask(AppMgrActivity.this).execute(b);
		}
		else {
			LogUtil.w(TAG, "Not system app");
			BgInstallApk.doInstallation(AppMgrActivity.this, filePath);
		}
	}

	/**
	 * 
	 * 更新当前apk下载进度
	 * 
	 * @param dLFileInfo
	 * @param speed
	 * @param progress
	 * @see [类、类#方法、类#成员]
	 */
	private void handleProgress(DLFileInfo dLFileInfo) {
		if (mFraglist.get(curPosition) instanceof UpdateAppFragment) {
			mUpdateAppFrag.updateAppDLProgress(dLFileInfo.getPkgName(), dLFileInfo.getProgress());
		}
		if (mFraglist.get(curPosition) instanceof DownloadingAppFragment) {
			mDownloadingAppFrag.updateAppDLProgress(dLFileInfo.getPkgName(), dLFileInfo.getProgress());
		}
	}

	/**
	 * 
	 * 解决下载过程中的错误
	 * 
	 * @param dLFileInfo
	 */
	public void handleError(DLFileInfo dLFileInfo, int errorCode, String errorInfo) {
		new DialogFactory(this).showDialog(getString(R.string.attention_error), errorInfo);
	}

	/**
	 * 增加下载任务
	 */
	public void addDLFile(DLFileInfo dLFileInfo) {
		LogUtil.d(TAG, "Add DL File() --> = " + dLFileInfo.getFilePath() + dLFileInfo.getFileName());
		DownloadHelper.addNewTask(AppMgrActivity.this, dLFileInfo, new DownloadHelper.PreDownloadStatusListener() {

			@Override
			public void sdCardCannotWriteOrRead(int errorCode, String errorInfo) {
				Toast.makeText(AppMgrActivity.this, "不能读写SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void notFoundSDCard(int errorCode, String errorInfo) {
				Toast.makeText(AppMgrActivity.this, "没有SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void moreTaskCount(int errorCode, String errorInfo) {
				Toast.makeText(AppMgrActivity.this, "任务列表已满", Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 
	 * 获取APK的下载URL
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	public void getDLUrl(AppInfo appinfo) {
		LogUtil.v(TAG, "startDL() -->");

		if (appinfo != null) {
			this.mAppInfo = appinfo;
			Bundle b = new Bundle();
			b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(appinfo.getAppId()));
			b.putString(HttpKeys.KEY_APPNAME, appinfo.getAppName());
			b.putString(HttpKeys.KEY_PACKAGENAME, appinfo.getPkgName());
			b.putString(HttpKeys.KEY_ICONURL, appinfo.getIconUrl());
			new GetAppUrlTask(this).execute(b);
		}
		else {
			LogUtil.e(TAG, "getDLUrl() --> mAppInfo is NULL");
		}

	}

	/**
	 * 
	 * 开始下载APK
	 * 
	 * @param apkurl
	 * @see [类、类#方法、类#成员]
	 */
	public void startDLAPK(String apkurl, String appName, String pkgName, String iconUrl, String appMD5) {

		DLFileInfo picFileInfo = new DLFileInfo();
		picFileInfo.setFilePath(ConfigUtil.FILE_PATH);
		picFileInfo.setFileUrl(apkurl);
		picFileInfo.setFileType("apk");
		picFileInfo.setPkgName(pkgName);
		picFileInfo.setFileName(appName + ".apk");
		picFileInfo.setIconUrl(iconUrl);
		picFileInfo.setMD5(appMD5);
		addDLFile(picFileInfo);
	}

	/**
	 * 检测正在下载的APK文件，并对比本地安装的应用去清除已安装的应用
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void checkInstalledDLApp() {
		List<DLFileInfo> urlList = ConfigUtil.getURLArray(this);
		if (urlList.size() >= 0) {
			for (int i = 0; i < urlList.size(); i++) {
				DLFileInfo dLFileInfo = urlList.get(i);
				if (dLFileInfo.getStatus() == DLFileInfo.STATUS_DOWNLOAD_END && AppUtils.checkAppInstallByPkgName(this, dLFileInfo.getPkgName())) {
					String filePath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
					PackageInfo uninstallApkInfo = AppUtils.getApkInfo(getApplicationContext(), filePath);
					if (uninstallApkInfo == null || uninstallApkInfo.versionName.compareTo(AppUtils.getVersion(getApplicationContext(), dLFileInfo.getPkgName())) <= 0) {
						LogUtil.e(TAG, "checkInstalledDLApp() --> clear Installed APK is " + dLFileInfo.getFileName());
						LogUtil.v(TAG, "checkInstalledDLApp() --> Delete APK = " + new File(filePath).delete());
						String index = Integer.toHexString(dLFileInfo.getFileUrl().hashCode());
						ConfigUtil.clearURL(getApplicationContext(), index);
					}
				}

			}
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (v instanceof CheckBox) {
			if (hasFocus) {
				switch (v.getId()) {
				case R.id.cb_app_installed:
					vp_fragment.setCurrentItem(0);
					break;
				case R.id.cb_app_downloading:
					vp_fragment.setCurrentItem(1);
					break;
				case R.id.cb_app_update:
					vp_fragment.setCurrentItem(2);
					break;
				default:
					break;
				}
			}
		}
	}

	public int getCurPosition() {
		return curPosition;
	}

}
